from flask import Flask,request,jsonify
from flask_cors import CORS
#对象关系映射
from flask_sqlalchemy import SQLAlchemy
from Config import Config
import json




app = Flask(__name__)
app.config.from_object(Config)
CORS(app)
db = SQLAlchemy(app)

class Ncate(db.Model):
    __tablename__='ncate'
    id = db.Column(db.Integer,primary_key=True,autoincrement=True)
    name = db.Column(db.String(40),default='')
    types = db.Column(db.Integer,default=1)
    parent = db.Column(db.Integer,default=0)
# db.create_all()
@app.route('/add_ncate',methods=['POST','GET','DELETE','PUT'])
def main():
    if request.method == 'POST':
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.form
        ncate = Ncate(name=data['name'])
        db.session.add(ncate)
        db.session.commit()
        return jsonify({'code':200})
    elif request.method == 'GET':
        ncate = Ncate.query.all()
        list1 = []
        for i in ncate:
            dict1 = {'id':i.id,'name':i.name,'types':i.types}
            list1.append(dict1)
        return jsonify({'code':200,'list':list1})
    elif request.method == 'DELETE':
        id = request.args.get('id')
        Ncate.query.filter_by(id=id).delete()
        db.session.commit()
        return jsonify({'code':200})
    else:
        id = request.args.get('id')
        name = request.args.get('name')
        Ncate.query.filter_by(id=id).update({'name':name})
        db.session.commit()
        return jsonify({'code':200})

    
if __name__ == '__main__':
    app.run(debug=True)